package com.wishu.finance.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wishu.finance.config.AjaxResult;
import com.wishu.finance.domain.*;
import com.wishu.finance.enums.AttachmentRelationTypeEnum;
import com.wishu.finance.enums.AttachmentTypeEnum;
import com.wishu.finance.enums.FinanceApplyStateEnum;
import com.wishu.finance.enums.FinanceProductTypeEnum;
import com.wishu.finance.service.*;
import com.wishu.finance.utils.MyJinRongUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("rent")
public class JrRentController {
    @Autowired
    TJrRentInstallmentService tJrRentInstallmentService;

    @Autowired
    TCfContractService tCfContractService;

    @Autowired
    TMAttachmentService tmAttachmentService;

    @Autowired
    TbBusinessService tbBusinessService;

    @Autowired
    TMCompanyAccountDetailService tmCompanyAccountDetailService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    TJrSfLoanService tJrSfLoanService;

    @Autowired
    TSfContractService tSfContractService;

    @Autowired
    TJrFactoringService tJrFactoringService;

    @Autowired
    TJrFactoringDetailService tJrFactoringDetailService;

    @GetMapping("list")
    public AjaxResult list(Page page, JrRentInstallmentSearch jrRentInstallmentSearch) {
        return AjaxResult.success(tJrRentInstallmentService.selectPageVo(page, jrRentInstallmentSearch));
    }

    @GetMapping("getType")
    public AjaxResult getType() {
        ArrayList<ProductType> list = new ArrayList<>();
        FinanceProductTypeEnum[] values = FinanceProductTypeEnum.values();
        for (FinanceProductTypeEnum value : values) {
            ProductType type = new ProductType();
            type.setId(value.getIndex());
            type.setName(value.getName());
            list.add(type);
        }
        return AjaxResult.success(list);
    }

    @GetMapping("getState")
    public AjaxResult getState() {
        ArrayList<ApplyState> list = new ArrayList<>();
        FinanceApplyStateEnum[] values = FinanceApplyStateEnum.values();
        for (FinanceApplyStateEnum value : values) {
            ApplyState state = new ApplyState();
            state.setId(value.getIndex());
            state.setName(value.getName());
            list.add(state);
        }
        return AjaxResult.success(list);
    }

    //应收租约保理审核不通过
    @GetMapping("test6")
    public AjaxResult test6(Integer applyState, Long id) {
        //判断是初审还是复审
        if (applyState == 1) {
            TJrFactoring rent = tJrFactoringService.getById(id);
            rent.setApplyState(3);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrFactoringService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        } else {
            TJrFactoring rent = tJrFactoringService.getById(id);
            rent.setApplyState(5);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrFactoringService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        }
    }

    //应收租约保理审核通过
    @GetMapping("test5")
    public AjaxResult test5(Integer applyState, Long id) {
        //判断是初审还是复审
        if (applyState == 1) {
            TJrFactoring sfLoader = tJrFactoringService.getById(id);
            sfLoader.setApplyState(2);
            sfLoader.setUpdateUserid(1L);
            sfLoader.setUpdateTime(new Date());
            boolean b = tJrFactoringService.updateById(sfLoader);
            return b ? AjaxResult.success() : AjaxResult.error();
        } else {
            TJrFactoring rent = tJrFactoringService.getById(id);
            rent.setApplyState(4);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrFactoringService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        }
    }

    //租房分期审核不通过
    @GetMapping("test4")
    public AjaxResult test4(Integer applyState, String cfContractId, Long id) {
        //判断是初审还是复审
        if (applyState == 1) {
            TJrSfLoan rent = tJrSfLoanService.getById(id);
            rent.setApplyState(3);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrSfLoanService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        } else {
            TJrSfLoan rent = tJrSfLoanService.getById(id);
            rent.setApplyState(5);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrSfLoanService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        }
    }

    //租房分期审核通过
    @GetMapping("test3")
    public AjaxResult test3(Integer applyState, Long id) {
        //判断是初审还是复审
        if (applyState == 1) {
            TJrSfLoan sfLoader = tJrSfLoanService.getById(id);
            sfLoader.setApplyState(2);
            sfLoader.setUpdateUserid(1L);
            sfLoader.setUpdateTime(new Date());
            boolean b = tJrSfLoanService.updateById(sfLoader);
            return b ? AjaxResult.success() : AjaxResult.error();
        } else {
            TJrSfLoan rent = tJrSfLoanService.getById(id);
            rent.setApplyState(4);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrSfLoanService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        }
    }

    //租房分期审核不通过
    @GetMapping("test2")
    public AjaxResult test2(Integer applyState, String cfContractId, Long id) {
        //判断是初审还是复审
        if (applyState == 1) {
            TJrRentInstallment rent = tJrRentInstallmentService.getById(id);
            rent.setApplyState(3);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrRentInstallmentService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        } else {
            TJrRentInstallment rent = tJrRentInstallmentService.getById(id);
            rent.setApplyState(5);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrRentInstallmentService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        }
    }

    //租房分期审核通过
    @GetMapping("test1")
    public AjaxResult test1(Integer applyState, Long id) {
        //判断是初审还是复审
        if (applyState == 1) {
            TJrRentInstallment rent = tJrRentInstallmentService.getById(id);
            rent.setApplyState(2);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrRentInstallmentService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        } else {
            TJrRentInstallment rent = tJrRentInstallmentService.getById(id);
            rent.setApplyState(4);
            rent.setUpdateUserid(1L);
            rent.setUpdateTime(new Date());
            boolean b = tJrRentInstallmentService.updateById(rent);
            return b ? AjaxResult.success() : AjaxResult.error();
        }
    }

    @GetMapping("rentingAuditView")
    public AjaxResult rentingAuditView(String cfContractId, Long id, String applyState, Integer jrProductType) {
        HashMap<String, Object> map = new HashMap<>();
        Long businessId = null;
        //租房分期
        if (jrProductType == FinanceProductTypeEnum.RENTMENT.getIndex()) {
            //租房分期详细信息
            JrRentInstallmentDetailsResponseDto installment = tJrRentInstallmentService.selectInstallmentDetails(id);
            //获取商户ID
            businessId = installment.getBussinessId();
            //获取合同信息
            ResponseDetailCfContractDto contractDetail = tCfContractService.detailCfContract(cfContractId);
            // 获取待收租金合计   还款账期*月租金= 待收租金合计
            BigDecimal totalMonthLimit = BigDecimal.ZERO;
            //承租月租金
            BigDecimal monthRent = contractDetail.getMonthRent();
            //还款账期
            Integer monthLimit = installment.getMonthLimit();
            // 计算合计
            totalMonthLimit = monthRent.multiply(new BigDecimal(monthLimit));
            // 利息 =应收租约合计* 租客承担比例 / 年化率  * 期数
            // 应收租约合计
            double reLeaseCount = Double.valueOf(installment.getReLeaseCount()).doubleValue();
            // 调用计算公式
            double periods = installment.getMonthLimit();
            //租客承担比例
            double tenantRate = MyJinRongUtils.div(installment.getTenantRate().doubleValue(), 100, 2);// 利率
            // 公寓分期利息合计
            double inInterestCount = Double.valueOf(installment.getInInterestCount()).doubleValue();
            // 计算利息
            double mul = MyJinRongUtils.mul(reLeaseCount, tenantRate);
            double div = MyJinRongUtils.div(mul, 12, 2);
            double rateCount_ = MyJinRongUtils.mul(div, periods);
            double rateCount = MyJinRongUtils.add(rateCount_, inInterestCount);
            // 月租金
            //租客合同url
            List<JrUrlResponseDto> contractUrl = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.ZLHT.getIndex(), Long.parseLong(cfContractId), AttachmentRelationTypeEnum.CFHT.getIndex());
            // 客户身份证复印件
            List<JrUrlResponseDto> cardurl = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.KHSFZ.getIndex(), Long.parseLong(cfContractId), AttachmentRelationTypeEnum.CFHT.getIndex());

            map.put("contractDetail", contractDetail);
            map.put("totalMonthLimit", totalMonthLimit);
            map.put("contractUrl", contractUrl);
            map.put("cardurl", cardurl);
            map.put("installment", installment);
            map.put("rateCount", rateCount);
            //收房贷
        } else if (jrProductType == FinanceProductTypeEnum.SFLOAN.getIndex()) {
            // 根据ID获取收房贷信息
            JrSfLoanDetailsResponseDto sfLoanDetail = tJrSfLoanService.selectSfLoanDetails(id);
            businessId = sfLoanDetail.getBusinessId();
            // 获取租客信息基本信息
            ResponseDetailSfContractDto contractDetail = tSfContractService.detailSfContract(cfContractId);
            // 计算租房分期  周期还款金额     收款方式的y * 月租金 =  周期还款金额
            BigDecimal cycleAmount1 = BigDecimal.ZERO;
            //收款方式（押X付Y的Y）
            Integer paymentType = contractDetail.getPaymentType();
            // 承租月租金
            // 周期还款金额  = 还款总额合计 /期数  rp_amount_count/month_limit
            String rpAmountCount = sfLoanDetail.getRpAmountCount();
            double parseDouble = Double.parseDouble(rpAmountCount);
            double cycleAmount = MyJinRongUtils.div(parseDouble, sfLoanDetail.getMonthLimit(), 2);
            // 查询租客户身份证复印件url
            List<JrUrlResponseDto> sfCardsUrl = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.YZSFZ.getIndex(), Long.parseLong(cfContractId), AttachmentRelationTypeEnum.SFHT.getIndex());
            // 查询收房贷合同url
            List<JrUrlResponseDto> sfDContractUrl = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.SFHT.getIndex(), Long.parseLong(cfContractId), AttachmentRelationTypeEnum.SFHT.getIndex());
            // 查询收房贷房产证url
            List<JrUrlResponseDto> sfDHouse = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.FCZ.getIndex(), Long.parseLong(cfContractId), AttachmentRelationTypeEnum.SFHT.getIndex());
            // 查询收房贷业主银行卡url
            List<JrUrlResponseDto> sfDBank = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.YHKXX.getIndex(), Long.parseLong(cfContractId), AttachmentRelationTypeEnum.SFHT.getIndex());

            map.put("sfLoanDetail", sfLoanDetail);
            map.put("cycleAmount", cycleAmount);
            map.put("contractDetail", contractDetail);
            map.put("sfCardsUrl", sfCardsUrl);
            map.put("sfDContractUrl", sfDContractUrl);
            map.put("sfDHouse", sfDHouse);
            map.put("sfDBank", sfDBank);
            //应收租约保理
        } else {
            // 租约保理申请详细信息
            List<JrFactoringDetailsResponseDto> factoringDetails = tJrFactoringService.selectFactoringDetails(id);
            // 租约保理申请查询
            TJrFactoring jrFactoring = tJrFactoringService.selectFactoring(id);
            businessId = Long.valueOf(jrFactoring.getBusinessId());

            map.put("factoringDetails", factoringDetails);
            map.put("jrFactoring", jrFactoring);
        }
        // 基本信息加载，商户信息
        ResponseDetailCompanyInfoDto detail = tbBusinessService.detailCompanyInfo(businessId);
        // 获取账户类型
        ResponseUpdateBankInfoDto bankInfo = tmCompanyAccountDetailService.queryBankInfo(businessId);
        // 获取用户名  手机号
        Long loginUserId = Long.valueOf("1");
        SysUser sysUser = sysUserService.getById(loginUserId);
        map.put("detail", detail);
        map.put("bankInfo", bankInfo);
        map.put("sysUser", sysUser);
        // 判断 融资申请审核操作 页面 审核按钮隐藏（显示）
        map.put("applyState_Show_Hidden", applyState);
        map.put("id", id);
        map.put("cfContractId", cfContractId);
        return AjaxResult.success(map);
    }

    @GetMapping("factoringDetailsView")
    public AjaxResult factoringDetailsView(String id, Long cfContractId, Long factoringId) {
        HashMap<String, Object> map = new HashMap<>();
        //根据合同ID获取合同的信息
        ResponseDetailCfContractDto contractDetail = tCfContractService.detailCfContract(String.valueOf(cfContractId));
        // 计算  周期还款金额     收款方式的y * 月租金 =  周期还款金额
        BigDecimal cycleAmount = BigDecimal.ZERO;
        //收款方式（押X付Y的Y）
        Integer paymentType = contractDetail.getPaymentType();
        // 承租月租金
        BigDecimal monthRent = contractDetail.getMonthRent();
        cycleAmount = monthRent.multiply(new BigDecimal(paymentType));

        // 通过ID查询租约保理申请信息
        TJrFactoring jrFactoring = tJrFactoringService.selectFactoring(factoringId);
        // 通过Id查询租约保理 详情
        TJrFactoringDetail jrFactoringDetail = tJrFactoringDetailService.getById(Long.parseLong(id));

        //计算 实收保理金额  保理授信额度-保理利息 -服务费 （%） = 实收宝理金额
        BigDecimal factoringTrueMoney = BigDecimal.ZERO;
        //  保理授信额度
        BigDecimal factoringCreditMoney = jrFactoringDetail.getFactoringCreditMoney();
        // 保理利息
        BigDecimal factoringInterest = jrFactoringDetail.getFactoringInterest();

        // 服务费 （%）
        BigDecimal serviceFee = jrFactoring.getServiceFee();
        float fee = serviceFee.floatValue();
        //  应收租约金额
        BigDecimal shouldMonthRent = jrFactoringDetail.getShouldMonthRent();
        // 服务费 除  设置默认值百分比
        BigDecimal feeRent = shouldMonthRent.multiply(new BigDecimal(fee / 100));
        BigDecimal oneServiceFee = feeRent.setScale(2, RoundingMode.HALF_UP);//保留两位小数
        BigDecimal subtract = factoringCreditMoney.subtract(factoringInterest);
        factoringTrueMoney = subtract.subtract(oneServiceFee);

        // 计算 退款金额      应收租约金额- 保理授信额度 =  退款金额
        BigDecimal refundAmount = BigDecimal.ZERO;
        refundAmount = shouldMonthRent.subtract(factoringCreditMoney);

        // 通过租约保理 申请Id 查询保理授信比例
        JrProductCreditLineResponseDTO jrProduct = tJrFactoringService.selectJrByCreditLine(factoringId);
        Double creditLine = jrProduct.getCreditLine();
        double creditLineValue = new BigDecimal(creditLine).setScale(2, RoundingMode.HALF_UP).doubleValue();//保留两位小数

        // 查询租客户身份证复印件url
        List<JrUrlResponseDto> jrCardsUrl = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.KHSFZ.getIndex(), cfContractId, AttachmentRelationTypeEnum.CFHT.getIndex());
        // 查询应收租约保理合同url
        List<JrUrlResponseDto> jrContractUrl = tmAttachmentService.selectAttachementUrlList(AttachmentTypeEnum.ZLHT.getIndex(), cfContractId, AttachmentRelationTypeEnum.CFHT.getIndex());

        map.put("creditLine", creditLineValue);
        map.put("cycleAmount", cycleAmount);
        map.put("factoringTrueMoney", factoringTrueMoney);
        map.put("refundAmount", refundAmount);
        map.put("oneServiceFee", oneServiceFee);
        map.put("jrCardsUrl", jrCardsUrl);
        map.put("jrCardsUrlCount", jrCardsUrl.size());
        map.put("jrContractUrl", jrContractUrl);
        map.put("jrContractUrlCount", jrContractUrl.size());
        map.put("contractDetail", contractDetail);
        map.put("jrFactoring", jrFactoring);
        map.put("jrFactoringDetail", jrFactoringDetail);

        return AjaxResult.success(map);
    }
}